package it.traveldreamWeb.customer;

import it.traveldream.dto.TransportMeanDTO;

import java.util.ArrayList;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

@FacesConverter(value="meanConverter")
public class MeanConverter implements Converter {

	private static List<TransportMeanDTO> means;
	
	public static void init(List<TransportMeanDTO> m){
		means = new ArrayList<>(m);
	}
	@Override
	public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {  
		if (submittedValue == null || submittedValue.trim().equals(""))   
            return null;  
          
        try{
        	for (TransportMeanDTO m : means){
        		if (m.getProductId().equals(Long.decode(submittedValue)))
        			return m;
        	}
        	return null;
        } catch(Exception exception) {  
            throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid mean"));  
        }    
    }  
  
	@Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {  
        String str = "";  
        if (value instanceof TransportMeanDTO)
        	str = "" + ((TransportMeanDTO)value).getProductId().toString();
        return str;
    } 

}
